<script setup lang="ts">
import { onMounted, ref, watch } from 'vue';
import { ElMessage, ElUpload } from 'element-plus';

// import chatAI from "./GPTchat.vue"
import { obsClient } from '@/utils/obs';
import { useAccountStore } from '@/stores/account';
import { resumeOpApi } from '@/api/path/resume';
import axios from 'axios';
import OpenAI from 'openai';

const pdfUrl = ref();
const resumeMsg = ref();


const client = new OpenAI({
    apiKey: import.meta.env.VITE_MOONSHOT_API_KEY,
    baseURL: 'https://api.moonshot.cn/v1',
    dangerouslyAllowBrowser: true,
});

const userInput = ref('');
const responseText = ref('');

  const history = ref([
    { role: 'system', content: '你是一个简历优化人员' },
  ]);
  
  const callAI = async (prompt: string): Promise<string> => {
    try {
      history.value.push({ role: 'user', content: prompt });
      const completion = await client.chat.completions.create({
        model: 'moonshot-v1-8k',
        messages: [...history.value], 
        temperature: 0.3,
      });
      return String(completion.choices[0].message.content); 
    } catch (error) {
      console.error('Error calling AI:', error);
      throw error; 
    }
  };
  
  
  const submit = async (input) => {
    userInput.value="";
    console.log("history",history.value)
    try {
      const reply = await callAI(input);
      console.log(reply)
      history.value.push({ role: 'assistant', content: reply });
      responseText.value = reply;
     
    } catch (error) {
    }
  };


watch(document.getElementById('pdf-file-input'), (newValue, oldValue) => { 
    op();
});


const op = () => {
    const fileInput = document.getElementById('pdf-file-input');
    fileInput.addEventListener('change', function(event) {
        // 获取文件
        const file = event.target.files[0];
        const formdata = new FormData();
        formdata.append("file",file)
        const url = URL.createObjectURL(file);
        pdfUrl.value = url;
        history.value.push({ role: 'assistant', content: "loading..." })
        if (file) {
            let url = 'http://localhost:5173/api/resumeopt_sys/optimize_resume/'
            let method = 'post'
            let headers =
                {
                'Content-Type': 'multipart/form-data'
                };
            axios({
            method,
            url,
            data: formdata,
            headers
            }).then(res => {
                if(res.data.errno===1){
                    history.value.push({ role: 'assistant', content: res.data.optimized_content });
                    resumeMsg.value = res.data.optimized_content
                }else {
                    history.value.push({ role: 'assistant', content: "请求次数过多" })
                }

                // console.log("resmsg",resumeMsg.value)
                
            })
        } else {
            console.log("No file selected.");
        }
    });
}
onMounted(()=>{
    op();
})
</script>

<template>
<div class="container">
    <el-row :gutter="20">
    <el-col :span="1">
    </el-col>
    <el-col :span="11">
        <el-affix :offset="80">
            <div class="resume-container" v-if="pdfUrl">
                <embed 
                :src="pdfUrl" 
                type="application/pdf" 
                class="pdf-container"/>
            </div>
            <el-empty v-else description="请上传PDF文件" style="height:83vh"/>
            <input type="file" id="pdf-file-input" accept=".pdf" />
        </el-affix>
    </el-col>
    <el-col :span="11">
        <el-card class="box-card">
            <div class="header">
            </div>
            <div class="chat-content" ref="chatContent">
                <!-- 用户输入和GPT回复的聊天气泡 -->
                <div v-for="(message, index) in history" :key="index" class="message">
                    <div  v-if="message.role!='system'" :class="['bubble', String(message.role)]">
                        {{ message.content }}
                    </div>
                </div>
            </div>
            <div class="input-area">
                <el-input
                v-model="userInput"
                type="textarea"
                placeholder="Please input"
                :autosize="{ minRows: 2, maxRows: 4 }"
                class="input-textarea"
                />
                <el-button 
                type="primary" 
                @click="submit(userInput)" 
                class="submit-button"
                >
                <el-icon><Top /></el-icon>
                </el-button>
            </div>
        </el-card>
    </el-col>
    <el-col :span="1">
    </el-col>
    </el-row>
</div>
</template>


<style scoped>
.box-card{
    background-color: white;
    border-radius: 15px;
    border: 2px solid var(--color-plain);
}
.el-row {
    margin-bottom: 20px;
}
.el-row:last-child {
    margin-bottom: 0;
}
.el-col {
    border-radius: 4px;
}

.grid-content {
    border-radius: 4px;
    min-height: 36px;
}
.container {
    width: 100%;
    padding: 10px;
    background-color: var(--color-light);
    min-height: 93vh;
}
.resume-container {
    width: 100%;
}
.pdf-container {
    width: 100%;
    min-height: 85vh;
    border: none;
}
.chat {
    min-height: 89vh;
}
.header {
    text-align: center;
}

.chat-content {
    overflow-y: auto;
    min-height: 70vh;
    background-color: #f9f9f9;
    padding: 20px;
    margin-bottom: 20px;
    border-radius: 15px;
    border: 2px solid var(--color-plain);
}

.message {
    margin-bottom: 20px;
    border-radius: 5px;
    background-color: #e6f5ff;
}

.bubble {
    padding: 10px;
    border-radius: 5px;
    max-width: 70%;
    clear: both;
}

.user {
    background-color: #e6f5ff;
    float: right;
}

.assistant {
  background-color: #ebf5f9;
  float: left;
}

.response {
  margin-top: 20px;
}

.response .bubble {
  background-color: #ebf5f9;
}
.input-area {
  display: flex;
  align-items: stretch; /* 使子元素高度一致 */
  width: 100%;
  margin: 0 auto;
  padding: 20px;
  box-sizing: border-box;
}

.input-textarea {
  flex-grow: 1; /* 使输入框占满剩余空间 */
}

.submit-button {
  margin-left: 10px;
  display: flex;
  align-items: center; /* 垂直居中对齐图标 */
  height: auto; /* 自动高度，使其与输入框高度一致 */
}
</style>